﻿package Chapter02;
// 將 StepIntoJava.java 內容替換為下列代碼即可運行
//======================================================================
//public class StepIntoJava {
//	public static void main(String[] args) {
//		Guess1A2B app = new Guess1A2B();
//		app.run();
//	}	
//}
//======================================================================

// 猜數字遊戲，課本範例的變形
public class Guess1A2B {
	Player p1;
	int[] targetNumber = {0,0,0,0};

	int aCount = 0;
	int bCount = 0;
	
	public void run() {
		p1 = new Player();
		
		String guessp1 = "";
		
		generateTargetNumber();
		System.out.println("I'm thinking of a number between 0 and 9...");
		
		while (true) {
			System.out.println("===============================");
			System.out.println("Number to guess is " + 
			targetNumber[0]+targetNumber[1]+targetNumber[2]+targetNumber[3]);
			
			p1.guessByInput();
			
			guessp1 = p1.strNumber;
			System.out.println("Player one guessed " + guessp1);
			
			// 檢查是否猜測正確
			checkGuess(guessp1);
			
			// 猜測之後的處理
			System.out.printf("%dA%dB\n", aCount, bCount);
			if (aCount == 4) {
				System.out.print("We have a winner: Player1");
				System.out.println("\nGame is over.");
				break;
			} else {
				System.out.println("Players will have to try again.");
			}
		}
		System.out.println("===============================");
	}

	private void generateTargetNumber() {
		for (int i = 0; i < targetNumber.length; i++) {
			boolean isOK = true;
			do {
				targetNumber[i] = (int)(Math.random() * 10);
				for (int j = 0; j < i; j++) {
					if (targetNumber[i] == targetNumber[j]) {
						isOK = false;
					}
				}
			} while (!isOK);
		}
	}
	
	private void checkGuess(String guess) {
		// 把 guess 拆成四個數字
		int[] guessNumber = {
				Integer.parseInt(guess.charAt(0)+""),
				Integer.parseInt(guess.charAt(1)+""),
				Integer.parseInt(guess.charAt(2)+""),
				Integer.parseInt(guess.charAt(3)+""),				
				};
		//int[] targetNumber;
		
		aCount = 0;
		bCount = 0;
		
		// 依照四個數字，分別去計算 A, B 的數目
		for (int i = 0; i < guessNumber.length; i++) {
			for (int j = 0; j < targetNumber.length; j++) {
				if (guessNumber[i]==targetNumber[j]) {
					if (i == j) {
						aCount++;
					} else {
						bCount++;
					}
					break;
				}
			}
		}
	}
}
